package register

import (
	"encoding/json"
	"github.com/sirupsen/logrus"
	"github.com/valyala/fasthttp"
	"log"
)

//节点查询自己的上报情况
type StatusHandler struct {
	client *Client
}

type GetNodeStatus struct {
	ID      string `json:"id"`
	SDPNum int    `json:"sdp_num"`
}

func (s *StatusHandler) Handle(message []byte) {
	s.client.jsonResponse(GetNodeStatus{
		ID:      s.client.nodeAnnounce.PeerId,
		SDPNum: len(s.client.nodeAnnounce.Sdps),
	})
}

func ServeStatus(server *Server, ctx *fasthttp.RequestCtx) {
	log.Printf("[ServeStatus]: begin ServeStatus")
	id := string(ctx.QueryArgs().Peek("id"))
	result := GetNodeStatus{
		ID: "",
		SDPNum: 0,
	}
	if id != "" {
		server.lock.Lock()
		peer, ok := server.clients[id]
		server.lock.Unlock()
		if ok {
			result.ID = peer.nodeAnnounce.PeerId
			result.SDPNum = len(peer.nodeAnnounce.Sdps)
		}

	}
	b, err := json.Marshal(result)
	if err == nil {
		ctx.Write(b)
		logrus.Infof("[ServeStatus] Write finish ")
		return
	} else {
		logrus.Errorf("[ServeStatus] Marshal err: %s", err.Error())
		ctx.Error("Server error", 500)
	}
}

//node preority
//isp ----  nat -- region

//00:1c:42:0b:de:24
